#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonArray>
#include <QThread>
#include <QWebEnginePage>
#include "WebReqHandler.h"
#include <core/QbLogger.h>

std::multimap<QString, WebHandlerFunc>   WebReqHandler::s_handlers;

WebReqHandler::WebReqHandler(QObject* parent)
    : QObject(parent)
{
}


void WebReqHandler::registerHandlers(const QString& req, WebHandlerFunc func)
{
    s_handlers.insert({req, func});
}

int  WebReqHandler::cefQuery(int sid, QJsonObject msg)
{
    QJsonDocument reqDoc(msg);
    QString reqStr = reqDoc.toJson();

    QString value = msg["request"].toString();
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(value.toUtf8(), &err);
    if (doc.isNull() || doc.isEmpty())
    {
#ifdef CCORE_MAC
        log_error("WEB REQ Parse ERROR! %s", err.errorString().toStdString().c_str());
#else
        log_error("WEB REQ Parse ERROR! %s", err.errorString().toUtf8());
#endif
        return -1;
    }
   
    QJsonArray reqArr = doc.array();
    if (!reqArr.isEmpty() && reqArr.size() > 1)
    {
        QString category = reqArr[0].toString();
        auto handlers = s_handlers.equal_range(category);
        for (auto iter = handlers.first; iter != handlers.second; ++iter)
        {
            WebResponse res;
            if (iter->second)
                res = iter->second(category, reqArr[1]);

            if (res.handled)
            {
                if(!res.res.isEmpty())
                    emit result(sid, res.res, res.jsCb);
                return 0;
            }
        }
    }
        
    return 0;
}
